<?php

namespace ImiApp\ApiServer\Common\Auth;

use Imi\Aop\AopManager;
use Imi\Bean\Annotation\AnnotationManager;
use Imi\Event\EventParam;
use Imi\Event\IEventListener;
use Imi\Bean\Annotation\Listener;
use Imi\Util\DelayClassCallable;
use Imi\Util\Imi;
use ImiApp\ApiServer\Common\AuthApi;
use ImiApp\ApiServer\Common\Auth\AuthApiAop;

/**
 * IMI暂不支持Aop切入类 查找类所有方法遍历切入
 * @Listener(eventName="IMI.LOAD_RUNTIME", priority=19940291)
 */
class AuthApiListener implements IEventListener
{
    /**
     * 切入所有使用Auth注解的类下的每个方法
     * @param EventParam $e
     * @return void
     */
    public function handle(EventParam $e): void
    {
        $authList = AnnotationManager::getAnnotationPoints(AuthApi::class);
        // var_dump('authList',$authList);
        foreach ($authList as $auth) {
     
            $class = $auth->getClass();
            $params = $auth->getAnnotation()->toArray();
            $configname = $params['name'];
            $nologin = $params['nologin'];
            // $nocheck = $params['nocheck'];
            $paramsArr = [$configname, $nologin];
            // var_dump('paramsArr',$paramsArr);
            if ($nologin !== '*') {
                $file = Imi::getNamespacePath($class);
                $fileContent = file(str_contains($file, '.php') ? $file : $file . '.php');
                $methods = [];
                foreach ($fileContent as $line) preg_match('~public function ([_A-Za-z0-9]+)~', $line, $regs) && $methods[] = $regs[1];
                $methods = array_diff($methods, (array)$nologin);
                // var_dump('methods',$methods);
                //$methods = array_diff(get_public_class_methods($class), (array)$nologin); get_public_class_methods这个玩应影响热更新 服了
                foreach ($methods as $method) {
                    $callback = new DelayClassCallable(AuthApiAop::class, 'parseAuthApi', $paramsArr);
                    AopManager::addAround($class, $method, $callback, 999, [
                        'deny' => [],
                        'extra' => $params
                    ]);
                }
            }
        }
    }
}